package com.cheryjb.examples.gwt.clock.client;

import java.util.Date;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * GWT Entry point.<br>
 * Init the Canvas, context, Clock and periodic screen refreshing.
 * 
 * @author Jean-Baptiste Chery
 * 
 */
public class ClockEntryPoint implements EntryPoint {

	// message displayed if your browser doesn't support HTML5 Canvas
	private static final String UPGRADE_MESSAGE = "Your browser does not support the HTML5 Canvas. Please upgrade your browser to view this demo.";
	// HTML div id where the canvas will be included
	private static final String CLOCK_DIV = "myClock";
	// pixel suffix
	private static final String PIXEL_EXT = "px";

	// Canvas width
	private static final int WIDTH = 240;
	// Canvas height
	private static final int HEIGHT = 240;
	// Refresh rate in milliseconds (200 displays 5 frames per second)
	private static final int REFRESH_RATE = 200;

	/**
	 * Canvas context where the scene is drawn
	 */
	private Context2d context;

	/**
	 * Object which is composite of several Drawable Objects: Clock Frame and
	 * Needles.
	 */
	private Clock clock;

	/**
	 * This is the entry point method.<br>
	 * Creates the Canvas, define the Canvas size, instantiate the Clock object
	 * and embed it in the div.
	 */
	@Override
	public void onModuleLoad() {
		final Canvas canvas = Canvas.createIfSupported();
		// if not supported, canvas is null
		if (canvas == null) {
			// Then we add a Label message in the HTML div to inform the User
			// that HTML5 Canvas is not supported
			RootPanel.get(CLOCK_DIV).add(new Label(UPGRADE_MESSAGE));
			return;
		}

		// set width and height of the HTML Canvas element
		canvas.setWidth(WIDTH + PIXEL_EXT);
		canvas.setHeight(HEIGHT + PIXEL_EXT);

		// define the coordinate space width and height inside the canvas
		// for example a 200x200 Canvas can have a 100x100 coordinate space.
		// Hence, 1 unit will be equals to 2 pixels
		canvas.setCoordinateSpaceWidth(WIDTH);
		canvas.setCoordinateSpaceHeight(HEIGHT);

		// retrieve the 2 dimensions Canvas context
		context = canvas.getContext2d();

		clock = new Clock();

		// add the Canvas in the HTML div
		RootPanel.get(CLOCK_DIV).add(canvas);

		final Timer timer = new Timer() {
			@Override
			public void run() {
				doUpdate();
			}
		};

		// each REFRESH_RATE ms, Timer run method is executed
		timer.scheduleRepeating(REFRESH_RATE);

	}

	/**
	 * redraw the scene, which fully depends on the date.
	 */
	void doUpdate() {
		// update the objects position
		clock.update(new Date());
		// clean up the scene
		context.clearRect(0, 0, WIDTH, HEIGHT);
		// redraw the scene
		clock.draw(context);
	}

}
